package yxy.game.pm2.module.shop.handle;

import org.joda.time.DateTime;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.actturntableshop;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.currency.CurrencyNotEnoughException;
import yxy.game.pm2.bean.db.dao.MySQLServerDAO;
import yxy.game.pm2.bean.db.module.server;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.message.ShopMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.player.FunctionHandle;
import yxy.game.pm2.module.shop.CreditRobShopModule;
import yxy.game.pm2.module.shop.Goods;
import yxy.game.pm2.module.shop.GoodsLimitType;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/** 商店 积分夺宝商店 */
public class CreditRobShopHandle extends ShopHandle<actturntableshop> {

	public void packResponse(String playerCode, ShopMessage.CreditRobShopResponse.Builder response) {
		CreditRobShopModule module = getModule(playerCode);
		module.canRefresh();
//		response.addAllGoods(goods(playerCode));
		response.setResetCost(new CurrencyHandle().packPoint(CreditRobShopModule.ShopRefreshCost()));
		response.setResetFree(module.getFreeTimes());
		response.setResetFreeTime(module.refreshTimesFreeTime());
//		response.setResetTimes(module.getResetTimes());
	}

	/** 手动刷新 */
	public Result refresh(String playerCode, ShopMessage.CreditRobShopUpdateResponse.Builder response) {
		CreditRobShopModule module = CreditRobShopModule.get(playerCode);
		if (!module.canRefresh()) {
			return Result.ShopCannotRefresh;
		}
		if (module.refreshFree()) {
			packRefresh(playerCode, module, response);
			return Result.Success;
		}
		Currency cost = CreditRobShopModule.ShopRefreshCost();// 刷新消费
		try {
			new CurrencyHandle().cost(playerCode, CCReason.商店, cost);
		} catch (CurrencyNotEnoughException e) {
			return new Result(Result.CostFail, e.getType().getNumber(), e.getDataId());// 消费不足
		}
		module.refresh();
		packRefresh(playerCode, module, response);
		return Result.Success;
	}

	private void packRefresh(String playerCode, CreditRobShopModule module, ShopMessage.CreditRobShopUpdateResponse.Builder response) {
        Collection<ShopMessage.Goods> goods = checkShopItemIsShow(playerCode);
        response.addAllGoods(goods);
		response.setResetCost(new CurrencyHandle().packPoint(CreditRobShopModule.ShopRefreshCost()));
		response.setResetFree(module.getFreeTimes());
		response.setResetFreeTime(module.refreshTimesFreeTime());
	}

    //根据开服时间和showtime过滤商品是否展示
	public Collection<ShopMessage.Goods> checkShopItemIsShow(String playerCode) {
        Collection<ShopMessage.Goods> goods = new CreditRobShopHandle().goods(playerCode);
        try {
            //商品表信息
            Map<String, actturntableshop> datas = DataCenter.getAllData(actturntableshop.class);
            ArrayList<String> idList = new ArrayList<>();
            //个人的商品信息
            //根据区id获取开服信息,计算已开服日期
            Long alreadlyPassTime = FunctionHandle.getAlreadlyPassTime(playerCode);
            //获取不展示的商品id集合
            Set<Map.Entry<String, actturntableshop>> entries = datas.entrySet();
            for (Map.Entry<String, actturntableshop> entry : entries) {
                int showtime = entry.getValue().getShowtime();
                //showtime不等于0且  已开服时间大于showtime才展示商品
                if (alreadlyPassTime - showtime < 0 || showtime == -1) {
                    idList.add(entry.getKey());
                }
            }

            //移除对应的不展示商品
            Iterator<ShopMessage.Goods> iterator = goods.iterator();
            while (iterator.hasNext()) {
                ShopMessage.Goods good = iterator.next();
                int id = good.getId();
                if(idList.contains(String.valueOf(id))){
                    iterator.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return goods;
    }

	public Long getAlreadlyPassTime(String playerCode) throws ParseException {
        //用户信息
        PlayerBean playerBean = PlayerBean.get(playerCode);
        //服id
        int serverId = playerBean.getServerId();
        //区服信息
        server server = MySQLServerDAO.getFromDAOAccountManager(serverId);
        //开服日期
        Date openTime = server.getOpenTime();
        //当前日期
        Date nowTime = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = simpleDateFormat.format(nowTime);
        String format2 = simpleDateFormat.format(openTime);
        Date now = simpleDateFormat.parse(format1);
        Date before = simpleDateFormat.parse(format2);
        long sub = Math.abs(now.getTime() - before.getTime());
        sub = sub / 1000 / 60 / 60 / 24;
        return sub;
    }


	public Result buy(String playerCode, int id, int num, ShopMessage.CreditRobShopBuyResponse.Builder response) {
		BuyResponse buyResponse = new BuyResponse();
		Result result = buy(playerCode, id, num, buyResponse);
		if (result.equals(Result.Success)) {
			response.setPurchase(buyResponse.getPurchase());
			response.setGoods(buyResponse.getGoods());
		}
		return result;
	}

	@Override
	public CreditRobShopModule getModule(String playerCode) {
		CreditRobShopModule module = CreditRobShopModule.get(playerCode);
		DateTime now = DateTime.now();
		boolean needSet = false;
		for (Goods goods : module.getGoods()) {
			needSet |= update(goods, now);
		}
		if (needSet) {
			module.set();
		}
		return module;
	}

	@Override
	public GoodsLimitType limitType(actturntableshop data) {
		return GoodsLimitType.forNumber(data.getLimittype());
	}

	@Override
	public int limit(actturntableshop data) {
		return data.getLimit();
	}

	@Override
	public int rebate(actturntableshop data) {
		return data.getReduce();
	}

	@Override
	public Currency cost(actturntableshop data, int num) {
		return Currency.create(data.getCosttype(), data.getCostid(), data.getCostnum() * num);
	}

	@Override
	public Currency purchase(actturntableshop data, int num) {
		return Currency.create(data.getShoptype(), data.getShopid(), data.getShopnum() * num);
	}

	@Override
	public Class<actturntableshop> clazz() {
		return actturntableshop.class;
	}
}